package org.chen.wordwave.act;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.PageWord;
import org.chen.wordwave.fragment.TestFragment;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.words.WordsUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

import cn.iwgang.countdownview.CountdownView;

public class Practice extends BaseActivity {

    CountdownView mCvCountdownView;
    ViewPager vp_test;

    private Map<Integer,Integer> trueWordList;

    private List<Fragment> fragments;
    private TextView tv_commit,tv_timu_number;

    private List<PageWord> pageWords;


    public static Map<Integer,Integer> userSelect =new LinkedHashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.practice_act;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void init() {

        mCvCountdownView = findViewById(R.id.cv_test);
        tv_commit = findViewById(R.id.tv_commit);
        tv_timu_number = findViewById(R.id.tv_timu_number);
        vp_test = findViewById(R.id.vp_test);
        mCvCountdownView.start(300000); // 毫秒
        mCvCountdownView.setOnCountdownEndListener(cv -> calculateScore());

        int wordsSize = WordInit.flyerSharedPreferences.getInt("TestNumberOfWords",24);
        pageWords = WordsUtils.getFlyerWords(wordsSize);
        tv_timu_number.setText(getString(R.string._1)+"/"+pageWords.size());
        trueWordList=new LinkedHashMap<>();
        fragments=new ArrayList<>();
        Random random=new Random();
        for (PageWord pageWord:pageWords){
            int trueIndex= random.nextInt(4)+1;
            trueWordList.put(pageWord.getCorrectWords().getId(),trueIndex);
            fragments.add(new TestFragment(pageWord,trueIndex));
//            初始化用户选择的结果集
            userSelect.put(pageWord.getCorrectWords().getId(),-1);
        }


        vp_test.setAdapter(new MyViewPagerAdapter(this.getSupportFragmentManager()));
        vp_test.setOffscreenPageLimit(wordsSize);
        vp_test.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tv_timu_number.setText(getString(R.string.question)+(position+1)+"/"+pageWords.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        tv_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (Integer i:userSelect.keySet()){
                    if (userSelect.get(i)==-1){
                        final AlertDialog.Builder normalDialog =
                                new AlertDialog.Builder(Practice.this);
                        normalDialog.setIcon(R.mipmap.wring);
                        normalDialog.setTitle(R.string.submit);
                        normalDialog.setMessage(R.string.no_sure_submit);
                        normalDialog.setPositiveButton(R.string.yes,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        calculateScore();
                                    }
                                });
                        normalDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        // 显示
                        normalDialog.show();
                        return;
                    }

                }
                calculateScore();
            }
        });
    }

    private void calculateScore() {
        //                当倒计时结束，直接提交试题，然后进行分数计算
        int trueWordsNumber =0 ;
        for (int i:trueWordList.keySet()){
            if (Objects.equals(userSelect.get(i), trueWordList.get(i))){
                trueWordsNumber++;
            }
        }
        double score = (double) trueWordsNumber / (double) pageWords.size() *100;
        score =(double)Math.round(score*10)/10;

        final AlertDialog.Builder normalDialog = getBuilder(score);
        // 显示
        normalDialog.show();
    }

    private AlertDialog.Builder getBuilder(double score) {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(Practice.this);
        normalDialog.setIcon(R.mipmap.word_ok);
        normalDialog.setTitle(R.string.score);
        normalDialog.setMessage(getString(R.string.YourScoreOnTheTestIs)+ score);
        normalDialog.setPositiveButton(R.string.yes,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Practice.this.finish();
                    }
                });
        return normalDialog;
    }


    class MyViewPagerAdapter extends FragmentPagerAdapter {


        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }
}

